/*
 * @Author: szx
 * @Date: 2022-02-12 13:53:25
 * @LastEditTime: 2022-02-12 14:11:11
 * @Description:
 * @FilePath: \leetcode\1000-1099\1020\1020.js
 */
/**
 * @param {number[][]} grid
 * @return {number}
 */
var numEnclaves = function (grid) {
    const dirs = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];
    const m = grid.length;
    const n = grid[0].length;

    const visited = new Array(m).fill(0).map(() => new Array(n).fill(false));

    const dfs = (row, col) => {
        if (row < 0 || row >= m || col < 0 || col >= n || grid[row][col] == 0 || visited[row][col]) return;
        visited[row][col] = true;
        for (let dir of dirs) {
            dfs(row + dir[0], col + dir[1]);
        }
    };
    for (let i = 0; i < m; i++) {
        dfs(i, 0);
        dfs(i, n - 1);
    }
    for (let j = 0; j < n; j++) {
        dfs(0, j);
        dfs(n - 1, j);
    }
    let res = 0;
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (grid[i][j] == 1 && !visited[i][j]) {
                res++;
            }
        }
    }
    return res;
};
